package com.snap.vseries.fragment;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;

import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.snap.vseries.AppConfig;
import com.snap.vseries.R;
import com.snap.vseries.base.BaseFragment;
import com.snap.vseries.bean.ExpInfo;
import com.snap.vseries.bean.TempBean;
import com.snap.vseries.chart.BarLineChartTouchListenerProxy;
import com.snap.vseries.chart.DebugTempFormatter;
import com.snap.vseries.chart.ELineChart;
import com.snap.vseries.chart.TimeFormatter;
import com.snap.vseries.chart.YAxisTempFormatter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.jessyan.autosize.utils.AutoSizeUtils;

@SuppressLint("ValidFragment")
public class ChartTempFragment extends BaseFragment {

    @BindView(R.id.chart)
    ELineChart chart;
    @BindView(R.id.chart_layout)
    LinearLayout chartLayout;
    @BindView(R.id.test_module_layout)
    LinearLayout testModuleLayout;

    private ExpInfo experimentInfo;

    public ChartTempFragment(ExpInfo experimentInfo) {
        this.experimentInfo = experimentInfo;
    }

    @Override
    protected int layoutResId() {
        return R.layout.fragment_chart_temp;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        ((DetailAnalyzeFragment) getParentFragment()).setGroupLlVisibility(View.GONE);
        hookChart();
        initViews();
        initData();
    }

    private void hookChart() {
        BarLineChartTouchListenerProxy proxy =
                new BarLineChartTouchListenerProxy(chart, chart.getViewPortHandler().getMatrixTouch(), 3f);
        chart.setOnTouchListener(proxy);
    }

    private void initViews() {
        //图表整体设置
        chart.setDrawGridBackground(false);//背景颜色
        chart.getDescription().setEnabled(false);//图表的描述信息
        chart.getLegend().setEnabled(false);//图例
        chart.setDrawBorders(false);//图表外边框
        chart.setMaxVisibleValueCount(0);

        //左右的两根Y轴配置
        chart.getAxisRight().setEnabled(false);
        YAxis yAxis = chart.getAxisLeft();//左面的Y轴
        yAxis.setEnabled(true);//开启
        yAxis.setDrawAxisLine(true);//绘制轴线
        yAxis.setDrawGridLines(true);//绘制网格线
        yAxis.enableGridDashedLine(9f, 4f, 0);
        yAxis.setAxisLineColor(0xffe8e9ee);
        yAxis.setGridColor(0xffe8e9ee);
        yAxis.setTextColor(0xff8d909f);
        yAxis.setTextSize(12f);
        yAxis.setValueFormatter(new YAxisTempFormatter());

        //y轴 坐标轴范围 缩放后最大最小坐标轴范围 以及最小分度值 网格线数量
        yAxis.setAxisMinimum(0);
        yAxis.setAxisMaximum(125 * 100);
        chart.setVisibleYRangeMinimum(120, YAxis.AxisDependency.LEFT);//放到最大坐标轴范围显示1.2°C
        yAxis.setGranularity(10f);
        yAxis.setLabelCount(8);

        //X轴配置
        XAxis xAxis = chart.getXAxis();
        xAxis.setEnabled(true);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置X轴位置在图表底部
        xAxis.setDrawAxisLine(true);
        xAxis.setDrawGridLines(true);
        xAxis.setGridColor(0xffe8e9ee);
        xAxis.setTextColor(0xff8d909f);
        xAxis.setTextSize(12f);
        xAxis.setValueFormatter(new TimeFormatter());

        //x轴 坐标轴范围 缩放后最大最小坐标轴范围 以及最小分度值 网格线数量
//        xAxis.setAxisMinimum(0);//如果是0，可以不调用
//        xAxis.setAxisMaximum();//无法确定 所以在设置数据后进行设置,也可以不调用，自动是数据集的size(设置数据集后）
//        chart.setVisibleXRangeMinimum(21);//这个值基于轴的总范围，轴最大范围未设置，或者没有数据集，此处设置就会失效，之后再行设置
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(7);

        //操作相关
        chart.setHighlightPerDragEnabled(false);
        chart.setHighlightPerTapEnabled(false);
        chart.setDoubleTapToZoomEnabled(false);
        chart.setKeepPositionOnRotation(true);
        chart.setTouchEnabled(true);
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setPinchZoom(true);

        chart.invalidate();
    }

    private void initData() {
        List<ILineDataSet> dataSets = new ArrayList<>();
        LineDataSet dataSet = new LineDataSet(new ArrayList<>(), "模块温度");
        //线的样式 宽 颜色等
        dataSet.setMode(LineDataSet.Mode.LINEAR);
        dataSet.setLineWidth(2f);
        dataSet.setColor(0x7fc9dafe);
        //线上的点、值
        dataSet.setDrawCircles(false);
        dataSet.setDrawValues(AppConfig.Dynamic.show_temp_value);
        dataSet.setValueTextSize(10);
        dataSet.setValueFormatter(new DebugTempFormatter());
        //填充
        dataSet.setDrawFilled(true);
        Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.fade_temp);
        dataSet.setFillDrawable(drawable);

        if (experimentInfo.getTempData() == null) {
            return;
        }
        List<TempBean> tempBeans = experimentInfo.getTempData().get(0);
        if (tempBeans != null) {
            for (int j = 0; j < tempBeans.size(); j++) {
                if (AppConfig.Dynamic.show_temp_value) {
                    dataSet.addEntry(new Entry(tempBeans.get(j).getSec(), tempBeans.get(j).getRealTemp()));
                } else {
                    dataSet.addEntry(new Entry(tempBeans.get(j).getSec(), tempBeans.get(j).getTemperature()));
                }
            }
        }
        dataSets.add(dataSet);


        //环境温度
        LineDataSet envDataSet = new LineDataSet(new ArrayList<>(), "模块温度");
        envDataSet.setMode(LineDataSet.Mode.LINEAR);
        envDataSet.setLineWidth(2f);
        envDataSet.setColor(getResources().getColor(R.color.primary_green));
        envDataSet.setDrawCircles(false);
        envDataSet.setDrawValues(false);
        List<TempBean> envTempBeans = experimentInfo.getTempData().get(0);
        if (envTempBeans != null) {
            for (int j = 0; j < envTempBeans.size(); j++) {
                envDataSet.addEntry(new Entry(envTempBeans.get(j).getSec(), envTempBeans.get(j).getTemperature()));
            }

        }
        dataSets.add(envDataSet);

        LineData lineData = new LineData(dataSets);
        chart.setData(lineData);

        chart.setVisibleXRangeMinimum(21);//放到最大 X轴范围 显示21个数据 即21个温度

        chart.invalidate();

        if (lineData.getEntryCount() > 0) {
            chartLayout.setVisibility(View.VISIBLE);
        }
    }

    private void addCheckBox(List<LineDataSet> lineDataSets) {
        testModuleLayout.setVisibility(View.VISIBLE);
        int size = lineDataSets.size();
        for (int i = 0; i < size; i++) {
            LineDataSet set = lineDataSets.get(i);
            CheckBox checkBox = new CheckBox(getContext());
            checkBox.setChecked(true);
            checkBox.setText(String.format("测试%d", i + 1));
            checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
                set.setVisible(isChecked);
                chart.invalidate();
            });
            checkBox.setPadding(AutoSizeUtils.dp2px(getContext(), 8),
                    AutoSizeUtils.dp2px(getContext(), 8),
                    AutoSizeUtils.dp2px(getContext(), 8),
                    AutoSizeUtils.dp2px(getContext(), 8));
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(AutoSizeUtils.dp2px(getContext(), 120), ViewGroup.LayoutParams.WRAP_CONTENT);
            checkBox.setLayoutParams(layoutParams);
            testModuleLayout.addView(checkBox);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            ((DetailAnalyzeFragment) getParentFragment()).setGroupLlVisibility(View.GONE);
        }
    }
}